import { Injectable, NgZone } from "@angular/core";
import { Router } from "@angular/router";
import { Platform } from "@ionic/angular";
import { AppGlobalService } from "./app-global.service";
import { EventService } from "./event.service";
import { HttpService } from "./http.service";
import { IndexedDBService } from "./indexed-db.service";
import * as CryptoJS from 'crypto-js';
import { Observable, EMPTY } from 'rxjs';
// import { PageModalService } from "./page-modal-service";
declare const $;

// tslint:disable
@Injectable({
  providedIn: "root",
})
export class ChatService {


  ws: WebSocket;
  pingStr = "ping";// "0x9";
  pongStr = "pong";// "0xA"; //overLogin
  pkey = "67ere9343lk"; // key/uid/size/number-yhy202309271000
  overLoginStr = "overLogin";
  lockReconnect = false;//重连标志位
  reconnectAttempts = 0; // 定义重试次数变量  
  maxReconnectAttempts = 3; // 定义最大重试次数 
  timeout = 1000 * 30; // 心跳检查设为55秒  2024.07.01 修改为30s
  serverTimeOut = 1000 * 5;// 
  sendtimeObj = null;
  serverTimeoutObj = null;
  pageSize = 20; // 每页取20条
  pageNo = 0;

  // WebSocket连接
  connection;
  WebSocketSession = null;
  // 当前状态是否连接
  connected = false;
  tmpInterval: any;
  // 当前登录的JID
  jid = "";
  messages: any;
  // 当前会话 ID
  sid = "";
  chatListArray = [];
  isPxw = this.appGlobalService.clientType;

  //	客户端
  // ws;
  mySid = "";
  account = localStorage.getItem('loginAccount');
  loginMode = "pc";
  currentGroupName = '';// 当前聊天室的名字
  currentTalkNo = "";// 当前谈话的ID
  currentTalkSource = "";
  currentGroup = false;

  myFriends = new Map();
  myGroups = new Map();
  groupMembers = new Map();
  newMsgMap = new Map();
  pluginId: any;
  pic: any;
  actionFromChatOnlinePage = false;
  insert = 0;
  enterTheChatRoomUseUserId = "";//默认值
  navigateUrl = '/chatOnline';

  sendEnterGroupCallBacktion: any;
  currentNeedAppendToGroupId: any; // 2023.12.04 
  enterGroupCallBacktion: any;// 2023.12.06

  public myFriendData: any[] = []; // 2024.07.26 我的好友

  public unreadFriendList = new Set(); //2024.08.09 未读消息列表 
  private cartItemCount = 0;
  public avatars: { [userId: string]: string } = {};
  public nickNames: { [userId: string]: string } = {};
  currentUserObj: any;
  defaultBase64String = '';

  lastPageItems: any[] = []; // 上次的列表数据
  lastTimeLine; // 上次的dateTimeLine


  loadDetailPage = (type, disableClick, pluginId, opportunity_id, activity_reg_id, url) => {
    // this.consoleLog('loadDetailPage=', type);
    if (disableClick !== undefined) {
      return;
    }
    const params = {
      plugin_id: pluginId, // 1:转让 2:出租 3: 选址
      type: type,
      session: localStorage.getItem('sessionId')
    };
    this.http.post('element/pageId/getBySession', params, (res) => {
      if (res) {
        if (res.status === "fail") {
          return;
        }
        const pageParams = {
          pageId: res.page,
          params: { opportunity_id: opportunity_id, activity_reg_id: activity_reg_id },
          sessionId: localStorage.getItem('sessionId')
        };
        this.appGlobalService.goToForward(pageParams);
      }
    });

  };// 防止页面点击无效
  constructor(
    private router: Router,
    private platform: Platform,
    private http: HttpService,
    public eventService: EventService,
    private indexedDBService: IndexedDBService,
    private appGlobalService: AppGlobalService,
    // public pageModalService: PageModalService,
    private ngZone: NgZone,
  ) {

    const that = this;
    this.connectting = this.debounce(this.afterDeBouncedConnectting.bind(this), 1000);
    this.appGlobalService.consoleLog('初始化chatService...', '');
    // 1.6.34 新增注册监听
    // 清除订阅
    try {
      // 1.初始化数据库
      this.indexedDBService.onPageLoad();
      // 2.关闭webSocket
      this.onLogoutWebSocket();
      // 3.im发送消息
      this.onSendWebSocket();
    } catch (error) {
      this.appGlobalService.consoleLog('error', error);
    }
    that.eventService.eventEmit.on('enterChatRoomByUserId', (obj) => {
      that.appGlobalService.consoleLog('enterChatRoomByUserId=', obj);
      if (localStorage.getItem('userId')) {
        if (obj.userId === localStorage.getItem('userId')) {
          that.appGlobalService.showToast('聊天账号异常！', 2000, 'middle');
          return;
        }
        if (obj && obj.userId !== undefined) {
          that.enterTheChatRoomUseUserId = obj.userId;
          that.unreadFriendList.delete(obj.userId); // 删除未读消息
          // 查看是否存在不存在则查询
          if (that.getAvatar(obj.userId)) {
            that.enterChatRoomByUserId(obj.userId, obj, obj.fromFriendList);
          } else {
            this.http.get(
              "message/userinfo/im/" + obj.userId,
              response => {
                const data = response.data;
                if (data) {
                  if (data.avatar_url === null) { // 没头像给默认头像
                    data.avatar_url = this.appGlobalService.defaultImg;
                    this.setAvatar(obj.userId, this.defaultBase64String);
                  } else {
                    this.appGlobalService.getBase64Str(data.avatar_url + "?x-oss-process=image/resize,h_36", str => {
                      this.setAvatar(obj.userId, str);
                    });
                  }
                  this.nickNames[obj.userId] = data.nickname;
                  that.enterChatRoomByUserId(obj.userId, {
                    userId: obj.userId,
                    fromFriendList: true,
                    friendName: data.nickname,
                    friendAvatar: data.avatar_url
                  }, true);
                }
              });

          }

        } else {
          that.enterTheChatRoomUseUserId = obj;
          that.unreadFriendList.delete(obj); // 删除未读消息
          that.enterChatRoomByUserId(obj, null);
        }
      } else {
        that.appGlobalService.showToast('网络异常！', 2000, 'middle');
        return;
      }
    });

    // 2024.08.05 清空好友
    that.eventService.eventEmit.on('clearMyFriendList', (obj) => {
      that.appGlobalService.consoleLog('clearMyFriendList ok...', obj);
      // that.setMyFriendData(null);
      that.myFriendData = [];
    });

  }


  public getMyFriendData() {
    let that = this;
    // if (localStorage.getItem('myFriendData')) {
    //   const tempMyFriendData = JSON.parse(localStorage.getItem('myFriendData'))
    // that.myFriendData = tempMyFriendData;
    // that.appGlobalService.consoleLog('getFriendDataFromLocalStorage=', that.myFriendData);
    // }
    return that.myFriendData;
  }



  async setMyFriendData(any) {
    let that = this;
    if (any && any.listData && any.listData.length > 0) {
      any.listData.forEach(item => {
        if (item) {
          if (item.friendAvatar === null) {
            item.friendAvatar = this.appGlobalService.defaultImg;
          }
          item.hasNoRead = that.unreadFriendList.has(item.friendNo);
          this.nickNames[item.friendNo] = item.friendName;
        }
      });
      that.myFriendData = any;
      that.appGlobalService.consoleLog('setMyFriendData=', that.myFriendData);
      any.listData.forEach((item, index) => {
        if (item && !this.getAvatar(item.friendNo)) {
          this.appGlobalService.getBase64Str(item.friendAvatar + "?x-oss-process=image/resize,h_36", str => {
            this.setAvatar(item.friendNo, str);
            this.appGlobalService.consoleLog(' set Avatar success ', index);
          });
        }
      });

    }

  }

  public getCartItemCount() {
    let that = this;
    return that.cartItemCount;
  }
  public setCartItemCount(count: any, updateDb?: any) {
    let that = this;
    const userId = localStorage.getItem('userId');
    this.appGlobalService.consoleLog('更新cart=', count);
    if (updateDb !== undefined && userId) {
      if (that.currentUserObj) {
        that.cartItemCount = count;
        that.currentUserObj.shopGoodsCartCount = count;
        this.indexedDBService.putByKeyCallbak(that.currentUserObj, userId, 'user', () => {
          this.appGlobalService.consoleLog('购物车数量修改成功', '');
        });
      } else {
        // 如果用户不存在，可以在这里处理，例如记录日志或抛出错误  
        this.appGlobalService.consoleLog('未找到用户，重新查表修改', '');
        this.http.get(
          "message/userinfo/im/" + userId,
          response => {
            const data = response.data;
            // 2024.08.02 联调接口返回参数
            if (count) {
              that.cartItemCount = count;
              data['shopGoodsCartCount'] = count;
            }
            this.indexedDBService.add(data, userId, "user");
          },
          error => {
            console.log("msg-----> error:" + JSON.stringify(error));
          }
        );
      }
    } else {
      // 表示已经存到库中只需要更新显示值
      this.cartItemCount = count;
      this.appGlobalService.consoleLog('购物车数量修改成功', '');
    }
  }
  // 2024.07.04 通过userId进入聊天详情
  enterChatRoomByUserId(queryId, friendInfo, fromFriendList?) {
    const that = this;

    // 2024.07.31 修改红点状态
    const tempFriendData = that.getMyFriendData();
    if (tempFriendData
      && tempFriendData['listData']
      && tempFriendData['listData'].length > 0) {
      const listData = tempFriendData['listData'];
      for (const element of listData) {
        if (element.friendNo === queryId) {
          element.hasNoRead = false;
        }
      }
    }
    // 2024.08.13 准备数据,从好友列表中进入的则已经带了好友数据，不是从好友列表进入的则查询一次存内存中
    const currentUserId = localStorage.getItem('userId');
    const item = {
      datetime: new Date().getHours() + ":" + new Date().getMinutes(),
      id: queryId + "-" + currentUserId,
      type: that.appGlobalService.clientType,
      toId: queryId,
    };
    let hiddenAddBtn = 'false';
    if (this.appGlobalService.hiddenAddBtn !== undefined) {
      hiddenAddBtn = this.appGlobalService.hiddenAddBtn;
    }

    item['groupNo'] = queryId;
    item['id'] = queryId + '-' + currentUserId;
    item['key'] = queryId + '-' + currentUserId;
    that.currentTalkNo = queryId;  // 
    // 1.从好友列表进入聊天详情
    if (fromFriendList !== undefined) {
      item['toUserAvatar'] = friendInfo.friendAvatar; // 接收方的头像
      that.currentGroupName = friendInfo.friendName; // 当前聊天室的名字就是接收方返回的。
      item['nickname'] = friendInfo.friendName;
      if (this.canSendMessage()) {
        this.goToChatOnlinePage(item);
      } else {
        // 状态异常则关闭之前的链接
        this.close();
        // 重新开启新的链接
        this.connectting(currentUserId, true, (eData) => {
          this.goToChatOnlinePage(item);
          this.appGlobalService.consoleLog('close old ws and coonect new ws! ', eData);
        });
      }
    }
    else {

    }



    // 2.其他入口进入聊天详情


    // 2024.08.13 进入聊天详情页面

    // that.http.get("message/userinfo/im/" + queryId, (response) => {
    //   if (response.status === 'success') {
    //     const data = response.data;
    //     this.appGlobalService.consoleLog('用户信息', data);
    //     that.currentGroupName = data.nickname; // 当前聊天室的名字就是接收方返回的。
    //     that.currentTalkNo = queryId;  // 
    //     // that.currentTalkNo = currentUserId;// 
    //     const item = {
    //       datetime: new Date().getHours() + ":" + new Date().getMinutes(),
    //       id: queryId + "-" + currentUserId,
    //       type: that.appGlobalService.clientType,
    //       toId: queryId,
    //     };
    //     let hiddenAddBtn = 'false';
    //     if (this.appGlobalService.hiddenAddBtn !== undefined) {
    //       hiddenAddBtn = this.appGlobalService.hiddenAddBtn;
    //     }
    //     item['toUserAvatar'] = data.avatar_url; // 接收方的头像
    //     item['groupNo'] = queryId;
    //     item['id'] = queryId + '-' + currentUserId;
    //     item['key'] = queryId + '-' + currentUserId;
    //     item['isNew'] = false;
    //     // 检查连接状态
    //     if (that.canSendMessage()) {
    //       that.goToChatOnlinePage(item);
    //     } else {
    //       // 2023.12.01 防止ws链接失效
    //       this.connectting(currentUserId, true, (eData) => {
    //         if (fromFriendList !== undefined) {
    //           that.goToChatOnlinePage(item);
    //           this.appGlobalService.consoleLog('connect success', eData);
    //         } else {
    //           this.appGlobalService.consoleLog('normal connectting', eData);
    //         }
    //       });
    //     }
    //   } else {
    //     that.appGlobalService.showToast('用户不存在', 2000, 'middle');
    //     that.appGlobalService.consoleLog('userId不存在', queryId);
    //   }
    // }, (error) => {
    //   that.appGlobalService.consoleLog('userId不存在', queryId);
    // });
  }
  // 跳转到聊天详情页面
  goToChatOnlinePage(item) {

    this.router.navigate(
      ["/chatOnline"],
      { queryParams: { item: JSON.stringify(item) } }
    );

  }


  //  检查WebSocket是否可以发送消息 2024.07.03 
  canSendMessage() {
    if (!this.ws) {
      return false;
    }
    return this.ws.readyState === 1; // 检查连接是否打开  
  }



  // 发送消息
  onSendWebSocket() {
    let that = this;
    this.eventService.eventEmit.on("onSendWebSocketMessage", (data) => {
      if (localStorage.getItem("onSendWebSocketMessageTag")) {
        localStorage.removeItem("onSendWebSocketMessageTag");
        setTimeout(() => {
          try {
            if (that.ws && that.ws.readyState === 3) {
              that.closeWebSocket();
            } else {
              that.sendMessage(data);
            }
          } catch (e) {
          }
        }, 200);
      }
    });
  }

  // 关闭会话
  onLogoutWebSocket() {
    const that = this;
    if (this.eventService.eventEmit.listenerCount("onLogoutWebSocket") > 0) {
      this.eventService.eventEmit.removeListener("onLogoutWebSocket");
    }
    this.eventService.eventEmit.on("onLogoutWebSocket", (data) => {
      if (localStorage.getItem("onLogoutWebSocketTag")) {
        localStorage.removeItem("onLogoutWebSocketTag");
        that.appGlobalService.consoleLog('关闭会话', '');
        that.closeWebSocket();
      }
    });
  }

  // 防抖函数  
  debounce(func, wait) {
    let timeout;
    return function (...args) {
      const context = this;
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        func.apply(context, args);
      }, wait);
    };
  }

  /*
  * 建立链接  isGetGroupInfo 是否获取群消息
  *
  */
  connectting(mySid, isGetGroupInfo = true, CallBackFunction) {
    this.appGlobalService.consoleLog('debounce connecting ...', '  	   ');
  }

  afterDeBouncedConnectting(mySid, isGetGroupInfo = true, CallBackFunction) {
    let that = this;
    const userIdAndKeyStr = this.pkey + localStorage.getItem('userId');
    const singStr = CryptoJS.MD5(userIdAndKeyStr).toString();
    this.platform.ready().then(() => {
      try {
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {

          if (this.ws && this.ws.readyState !== WebSocket.CLOSED) {
            this.ws.close();
          }

          // 如果没有 WebSocket 实例或当前实例未打开，则创建一个新的  
          const wsUrl = this.http.wsServiceAPI + localStorage.getItem('userId') + '/' + singStr;
          this.appGlobalService.consoleLog('wsUrl=', wsUrl);
          this.ws = new WebSocket(wsUrl);

          // 设置 WebSocket 事件监听器  
          this.ws.onmessage = (e) => {
            // 处理接收到的消息  
            if (e.data === this.pongStr) {
              this.appGlobalService.consoleLog('receive pong', '  	   ');
              that.start();
            } else {
              try {
                const eRespData = JSON.parse(e.data);
                if (eRespData.content && eRespData.content.code === 200) {
                  that.start();
                  that.appGlobalService.consoleLog('启动心跳', '');
                  CallBackFunction(true);

                } else {
                  if (that.currentTalkNo !== undefined && that.currentTalkNo === eRespData.from) {
                    that.onReceiveMessage(eRespData, null, CallBackFunction);
                  } else {
                    that.onReceiveMessage(eRespData, that.currentTalkNo, CallBackFunction);
                  }
                  that.appGlobalService.consoleLog('收到普通消息', eRespData.content);
                  // CallBackFunction(null);
                }
              } catch (error) {
                that.appGlobalService.consoleLog('解析服务器消息出错', error);
                CallBackFunction(null);
              }
            }
          };

          this.ws.onerror = (error) => {
            // 处理错误  
            that.appGlobalService.consoleLog('连接出错', error);
            // that.appGlobalService.showToast('网络连接不通畅，请稍等！', 2000, 'middle');
            this.appGlobalService.consoleLog('网络连接不通畅，请稍等！', '  	   ');
            if (!that.appGlobalService.isPreview) {
              if (localStorage.getItem('loginStatus') === null) {
                this.appGlobalService.consoleLog('系统：用户登录状态异常', '  	   ');
                return;
              }
              this.appGlobalService.consoleLog('系统：onerror reconnect', '  	   ');
              this.attemptReconnect();
            }
            CallBackFunction(null);
          };

          this.ws.onclose = (e) => {
            // 处理关闭事件  
            this.appGlobalService.consoleLog('系统: 关闭连接!', e);
            this.attemptReconnect();
            // 可能需要在这里实现自动重连逻辑  
            // ...  
            CallBackFunction(null);
          };

          this.ws.onopen = function () {
            that.appGlobalService.consoleLog('系统: 正在连接中...', '');
          }
        }
      } catch (error) {
        this.appGlobalService.consoleLog('connectting error', error);
      }
    });
  }


  onReceiveMessage(data, currentTalkNo, callBackFunction) {
    let that = this;
    // 
    //   {
    //     "fromUser": {
    //         "nickName": "深圳叶工",
    //         "avatar": "",
    //         "category": "user"
    //     },
    //     "header": "message",
    //     "from": "3a2a422d0f9c11eab63a0242ac160002",
    //     "content": ""
    // }
    const msg = data;
    let datetime = that.appGlobalService.getNowFormatDateYYYYMMDDHHMM();
    const jid = localStorage.getItem("userId");
    const msgBox = JSON.parse(msg.content);
    const body = msgBox;
    const currentPath = localStorage.getItem('currentPath');

    if (currentTalkNo === '') { //  收信方userId为空表示暂未和任何好友聊天
      // 展示div
      if (msg.from !== localStorage.getItem('userId')) {
        that.currentTalkNo = msg.from;
        // 2023.12.01
        that.appGlobalService.isShowMessageNotifyDiv = true;//TODO
        that.appGlobalService.showMessageBody = body.message;
        that.appGlobalService.showMessageDateTime = that.getFormatImDate(datetime);
      }

      if (!that.getAvatar(msg.from)) {
        that.appGlobalService.getBase64Str(msg.fromUser.avatar + "?x-oss-process=image/resize,h_36", str => {
          // that.setAvatar(userId, str);
          that.setAvatar(msg.from, str);
        });
      }

      //播放声音
      const player = document.getElementById('showMessageNotifyAudio') as HTMLAudioElement;
      if (player) {
        if (player.canPlayType) {

          if (currentPath !== null && currentPath !== 'chatOnline') {
            if (player.paused) {
              player.play();
            }
          } else if (currentPath === null) {
            if (player.paused) {
              player.play();
            }
          }
        }
      }

      // 添加点击事件
      setTimeout(() => {
        const messageNotifyDiv = document.getElementById('notifyInnerBox');
        if (messageNotifyDiv) {
          messageNotifyDiv.addEventListener('scroll', that.homeMessageScroll, false);
          if (document.getElementById('notifyBox')) {
            document.getElementById('notifyBox').addEventListener('click', (e) => {
              that.homeMessageClick(e, msg.from, msg.fromUser);
            }, false);
          }
        }
      }, 2000);

      // 隐藏消息弹窗
      setTimeout(() => {
        $('#messageNotify').fadeOut(600);
        $('#notifyBox').fadeOut(600);
        that.appGlobalService.isShowMessageNotifyDiv = false;
      }, 4000);


      // 2024.07.31 更新红点状态  
      const tempFriendData = that.getMyFriendData();
      if (tempFriendData && tempFriendData['listData'] && tempFriendData['listData'].length > 0) {
        let listData = tempFriendData['listData'];
        let foundMatch = false;
        for (const friend of listData) {
          if (friend.friendNo === msg.from) {
            friend.hasNoRead = true;
            foundMatch = true;
            that.setMyFriendData(tempFriendData); // 实时更新红点状态  
            break;
          }
        }

        // 如果没有找到匹配项，说明是新的聊天好友  
        if (!foundMatch) {
          const userId = localStorage.getItem('userId');
          const pageSize = that.pageSize;
          const pageNo = that.pageNo;
          const url = `${that.http.talkQueryFriendsList}${that.getPaginationParamStr(userId, pageSize, pageNo)}`;
          this.getGetData(url, (response) => {
            if (response) {
              const data = JSON.parse(response);
              if (data && data.listData) {
                this.appGlobalService.consoleLog('过滤新列表', '  	   ');
                // 如果旧的listData有值
                if (listData && listData.length > 0) {
                  const filteredList = data.listData.filter(newItem => !listData.some(oldItem => oldItem.friendNo === newItem.friendNo));
                  // 将过滤后的新数据中的每个元素的hasNoRead改为true  
                  filteredList.forEach(item => {
                    item.hasNoRead = true;
                  });
                  // 将过滤后的新数据添加到listData的前端  
                  listData = filteredList.concat(listData);
                  tempFriendData['listData'] = listData;
                  that.setMyFriendData(tempFriendData); // 更新数据  
                } else {
                  // 没有获取到值则取当前这一条
                  listData = data.listData;
                  for (let index = 0; index < listData.length; index++) {
                    const element = listData[index];
                    if (element.friendNo = msg.from) {
                      element.hasNoRead = true;
                      listData[index] = element;
                      tempFriendData['listData'] = listData;
                      that.setMyFriendData(tempFriendData); // 更新数据
                      break;
                    }
                  }
                }
              }
            }
          });
        }
      }
    } else {
      setTimeout(async () => {
        const msgType = body.type;
        const pluginId = "1"; // 1 转让 2 求租 3 招租
        let opportunityId = 0;
        const title = "";
        const pic = "";
        if (msgType === "opp") {
          opportunityId = 0;
          this.pluginId = body.pluginId;
          this.pic = body.imags;
        } else if (msgType === "case") {
          this.pic = body.pic;
        }

        let tel = "";
        if (msgType === "general") {
          try {
            // 新增临时需求
            if (body.message.includes("&lt;font color=#499DF2 &gt;")) {
              const startPos =
                body.message.search("tel:&lt;font color=#499DF2 &gt;") +
                31;
              tel = body.message.substring(startPos, startPos + 11);
              const afterReplaceText =
                "<font color=#499DF2 >" + tel + "</font>";
              const replaceTel =
                "tel:&lt;font color=#499DF2 &gt;" +
                tel +
                "&lt;/font&gt;";
              body.message = body.message.replace(
                replaceTel,
                afterReplaceText
              );

              body["tel"] = tel;
              if (that.appGlobalService.clientType === "pxw") {
                setTimeout(() => {
                  that.http.changeCallNumber(tel);
                }, 800);
              }
            } else {
              if (body.message.includes("tel:")) {
                const startPos = body.message.search("tel:") + 4;
                tel = body.message.substring(startPos, startPos + 11);
                const afterReplaceText =
                  "<font color=#499DF2 >" + tel + "</font>";
                body.message = body.message.replace(
                  tel,
                  afterReplaceText
                );

                body["tel"] = tel;
                if (that.appGlobalService.clientType === "pxw") {
                  setTimeout(() => {
                    that.http.changeCallNumber(tel);
                  }, 800);
                }
              }
            }
          } catch (error) {
            tel = "";
          }
        }

        let message =
          msgType === "general"
            ? {
              id: msg.from + "-" + jid,
              senderId: msg.from,
              text: body,
              type: msgType,
              time: datetime,
            }
            : msgType === "opp"
              ? {
                id: msg.from + "-" + jid,
                senderId: msg.from,
                type: msgType,
                rentunit: body.rentunit ? body.rentunit : "元/月",
                opportunity_id: opportunityId,
                activity_reg_id: data.activity_reg_id,
                title: body.title,
                pic: body.imags,
                pluginId,
                time: datetime,
                disableClick: body.disableClick === undefined ? false : true,
                big_district: body.big_district,
                district: body.district,
                area: body.area,
                industry:
                  this.pluginId === "1" ? body.industry : body.build,
                rent: body.rent,
                transfer_fee: body.transfer_fee
                  ? body.transfer_fee
                  : undefined,
              }
              : {
                id: msg.from + "-" + jid,
                senderId: msg.from,
                type: msgType,
                title: body.title,
                imags: body.imags,
                time: datetime,
                district: body.district,
                serviceOpinion: body.serviceOpinion,
                serviceDays: body.serviceDays,
                industry: body.industry,
              };
        const storageKey = msg.from + "-" + jid;

        const unreadGeneralMsg = {
          msg: {
            type: "general",
            message: body.message,
            from: msg.from,
            tel,
          },
          datetime,
          number: 1,
          isNew: 1,
          updateTime: new Date().getTime(),
          key: storageKey
        };

        if (!that.getAvatar(msg.from)) {
          that.appGlobalService.getBase64Str(msg.fromUser.avatar + "?x-oss-process=image/resize,h_36", str => {
            // that.setAvatar(userId, str);
            that.setAvatar(msg.from, str);
          });
        }

        const unreadOppMsg = {
          msg: { type: "opp", message: message.title, from: msg.from },
          datetime,
          number: 1,
          isNew: 1,
          updateTime: new Date().getTime(),
          key: storageKey
        };

        const unreadCaseMsg = {
          msg: { type: "case", message: message.title, from: msg.from },
          datetime,
          number: 1,
          isNew: 1,
          updateTime: new Date().getTime(),
          key: storageKey
        };


        //2024.08.10 收到消息更新 recevieMsgLastTime
        localStorage.setItem('recevieMsgLastTime', new Date().getTime().toString());

        if (msg.from !== localStorage.getItem('userId')) {
          // 2023.12.01
          that.appGlobalService.isShowMessageNotifyDiv = true;//TODO
          that.appGlobalService.showMessageBody = body.message;
          that.appGlobalService.showMessageDateTime = that.getFormatImDate(datetime);
        }

        const player = document.getElementById('showMessageNotifyAudio') as HTMLAudioElement;


        // 2024.08.09 不在聊天详情页面处理红点
        if (currentPath === null || (currentPath !== null && currentPath !== 'chatOnline')) {
          that.unreadFriendList.add(msg.from);
          this.appGlobalService.consoleLog('unread userid = ', msg.from);
        } else if (currentPath !== null && currentPath === 'chatOnline') {
          // 如果当前在聊天详情页面并且发送方不是当前正在聊天的对象
          if (msg.from !== that.currentTalkNo) {
            that.unreadFriendList.add(msg.from);
            this.appGlobalService.consoleLog('unread userid != currentTalkNo ', msg.from);
          }
        }
        // 蜂喔1.6.15 聊天详情页面不 播放声音
        if (player) {
          if (player.canPlayType) {

            if (currentPath !== null && currentPath !== 'chatOnline') {
              if (player.paused) {
                player.play();
              }
            } else if (currentPath === null) {
              if (player.paused) {
                player.play();
              }
            } else if (currentPath === 'chatOnline') {
              if (msgBox && msgBox.clientSendTime) {
                that.appGlobalService.addedMessages.add(msgBox.clientSendTime);
              }
            }
          }
        }
        setTimeout(() => {
          const messageNotifyDiv = document.getElementById('notifyInnerBox');
          if (messageNotifyDiv) {
            messageNotifyDiv.addEventListener('scroll', that.homeMessageScroll, false);
            if (document.getElementById('notifyBox')) {
              document.getElementById('notifyBox').addEventListener('click', (e) => {
                that.homeMessageClick(e, msg.from, msg.fromUser);

              }, false);
            }
          }
        }, 2000);
        setTimeout(() => {
          $('#messageNotify').fadeOut(600);
          $('#notifyBox').fadeOut(600);
          that.appGlobalService.isShowMessageNotifyDiv = false;
        }, 4000);
        if (msg.from === this.currentTalkNo) {
          this.appGlobalService.consoleLog('msg.from === this.currentTalkNo ', '  	   ');
          // 2023.12.01 接收消息
          msg['speaker'] = msg.from;
           
          this.addFriendContentView(msg, msgType, JSON.stringify(body),new Date().getTime().toString(),true);
        }

        //2023.12.04 收到消息刷新邀约列表
        // console.log('收到消息!', new Date().toLocaleDateString());
        // that.eventService.eventEmit.emit('refreshChatInviteList', '1');

        // 2024.07.31 更新红点状态  
        const tempFriendData = that.getMyFriendData();
        if (tempFriendData.length === 0 || (tempFriendData && tempFriendData['listData'] && tempFriendData['listData'].length > 0)) {
          let listData = tempFriendData['listData'];
          let foundMatch = false;
          if (listData) {
            for (let index = 0; index < listData.length; index++) {
              const friend = listData[index]
              if (friend && friend.friendNo === msg.from) {
                friend.hasNoRead = true;
                listData[index] = friend;
                tempFriendData['listData'] = listData;
                foundMatch = true;
                that.setMyFriendData(tempFriendData); // 实时更新红点状态  
                break;
              }
            }
          }


          // 如果没有找到匹配项，说明是新的聊天好友  
          if (!foundMatch) {
            const userId = localStorage.getItem('userId');
            const pageSize = that.pageSize;
            const pageNo = that.pageNo;
            const url = `${that.http.talkQueryFriendsList}${that.getPaginationParamStr(userId, pageSize, pageNo)}`;
            this.getGetData(url, (response) => {
              if (response) {
                const data = JSON.parse(response);
                if (data && data.listData) {
                  this.appGlobalService.consoleLog('过滤新列表', '  	   ');

                  if (listData && listData.length > 0) {
                    const filteredList =
                      data.listData.filter(newItem =>
                        !listData.some(oldItem =>
                          oldItem.friendNo === newItem.friendNo));
                    // 将过滤后的新数据中的每个元素的hasNoRead改为true  
                    filteredList.forEach(item => {
                      item.hasNoRead = true;
                    });
                    // 将过滤后的新数据添加到listData的前端  
                    listData = filteredList.concat(listData);
                    tempFriendData['listData'] = listData;
                    that.setMyFriendData(tempFriendData); // 更新数据  
                  } else {
                    // 没有获取到值则取当前这一条
                    listData = data.listData;
                    for (let index = 0; index < listData.length; index++) {
                      const element = listData[index];
                      if (element.friendNo = msg.from) {
                        element.hasNoRead = true;
                        listData[index] = element;
                        tempFriendData['listData'] = listData;
                        that.setMyFriendData(tempFriendData); // 更新数据
                        break;
                      }
                    }
                  }
                }
              }
            });
          }
        }
      }, 200);
    }


    setTimeout(() => {
      callBackFunction(true);
    }, 300);
  }


  reconnect(fromOnResume?) {

    if(fromOnResume===undefined){
      this.http.delayShowLoading();
    }

    // 重连前确保关闭旧的连接  
    this.appGlobalService.consoleLog('重连前确保关闭旧的连接', '  	   ');
    if (this.ws) {
      this.ws.close();
      // this.ws.onclose = () => {
      //   // WebSocket 连接已经关闭，现在可以进行重连  
      //   this.appGlobalService.consoleLog('连接已经关闭，现在可以进行重连', '  	   ');
      //   this.attemptReconnect();

      // };
      // // 还可以添加一个onerror事件处理，以防close时触发错误  
      // this.ws.onerror = (error) => {
      //   this.appGlobalService.consoleLog('以防close时触发错误', '  	   ');
      //   console.error('WebSocket close error:', error);
      //   // 即使出错，也尝试重连  
      //   this.attemptReconnect();
      // };
    } else {
      // 如果没有旧的 WebSocket 连接，直接尝试重连  
      this.attemptReconnect();
    }
  }

  attemptReconnect() {
    this.appGlobalService.consoleLog('开始尝试重连...', '  	   ');
    const that = this;
    if (this.lockReconnect) {
      this.appGlobalService.consoleLog('lockReconnect is true return', '  	   ');
      return;
    }
    if (that.reconnectAttempts >= that.maxReconnectAttempts) {
      this.appGlobalService.consoleLog('已达到最大重试次数', '  	   ');
      // that.appGlobalService.showToast('网络不通畅！', 2000, 'middle');
      if (localStorage.getItem('currentPath') === 'chatOnline') {
        that.appGlobalService.goBack();
      }
      return;
    }
    this.lockReconnect = true;
    if (localStorage.getItem('loginStatus') === null) {
      this.lockReconnect = false;
      this.appGlobalService.consoleLog(' loginStatus === null 	   ', '  	   ');
      return;
    }
    setTimeout(() => {
      this.connectting(localStorage.getItem('loginAccount'), true, (eData) => {
        that.lockReconnect = false;
        if (eData !== null && eData) {
          that.appGlobalService.consoleLog('系统：重连成功！', '');
          that.reconnectAttempts = 0; // 初始化重连次数  
        } else {
          that.appGlobalService.consoleLog('reconnectAttempts=', that.reconnectAttempts);
          that.reconnect(); // 递归调用以尝试再次重连  
        }
        this.http.hideLoading();
      });
      that.reconnectAttempts++; // 每次重连后，重试次数加1  
    }, 5000); // 延迟5秒重连  
  }

  // 重连-异常或者被关闭后隔5秒钟进行重连
  // reconnect() {
  //   this.http.delayShowLoading();
  //   // 重连前确保关闭旧的连接
  //   if (this.ws) {
  //     this.ws.close();
  //   }
  //   const that = this;
  //   if (this.lockReconnect) {
  //     return;
  //   }
  //   if (that.reconnectAttempts >= that.maxReconnectAttempts) {
  //     console.log('已达到最大重试次数');
  //     // 预览不占用重连资源
  //     that.appGlobalService.showToast('网络不通畅！', 2000, 'middle');
  //     const currentPath = localStorage.getItem('currentPath');
  //     if(currentPath === 'chatOnline'){
  //       that.appGlobalService.goBack();
  //     }
  //     return;
  //   }
  //   this.lockReconnect = true;
  //   if (localStorage.getItem('loginStatus') === null) {
  //     this.lockReconnect = false;
  //     return;
  //   }
  //   setTimeout(() => {
  //     this.connectting(localStorage.getItem('loginAccount'), true, (eData) => {
  //       that.lockReconnect = false;
  //       if (eData !== null && eData) {
  //         that.appGlobalService.consoleLog('系统：重连成功！', '');
  //         that.reconnectAttempts = 0; // 初始化重连次数
  //       } else {
  //         that.appGlobalService.consoleLog('reconnectAttempts=', that.reconnectAttempts);
  //         that.reconnect();
  //       }
  //       this.http.hideLoading();
  //     });
  //     that.reconnectAttempts++; // 每次重连后，重试次数加1     
  //   }, 1000 * 5 * 1);
  // }


  // 添加我发送的内容
  addMyContentView(msgType, content, createTime?,fromSend?) {
    const that = this;
    let viewitem = ""
    const contentObj = JSON.parse(content);
    if (contentObj.type) {
      msgType = contentObj.type;
    }
    let oppDivId = '';
    if (msgType == "string" || msgType === "general") {
      viewitem = "<div class=\"talkItem\" style=\"display: flex;width: 100%;justify-content: flex-end;margin-bottom: 1rem;\"> <div style=\"width: 3.5rem; height: 0.625rem;\"></div> "
        + " <div class=\"talkcontent  myTalkContent\"  style=\"font-weight: 400;color: #252629;display: inline-block;vertical-align: top;text-align:left;background: #ffe700;width: -moz-fit-content;width: max-content;max-width: 14.69rem;min-width:5rem;font-size: 1rem;line-height: 1.38rem;padding: 0.56rem 1rem;position: relative;white-space: pre-line;border-radius: 0.5rem 0 0.5rem 0.5rem;\"> "
        + contentObj.message
        + " </div> <div class=\"avatorpanel\" "
        + "style=\"display: flex;flex-direction: column;align-items: center;margin-left: 0.5rem;\" "
        + "><a class=\"talkavator\">" + "<div class=\"windowImg marginR15L10\">"
        + "<img class=\"windowImg\" src=\"" +
        localStorage.getItem('currentAvatarStr')
        + "\""
        + "style=\"object-fit:unset;object-position: center;width: 2.5rem;height: 2.5rem;border-radius: 50%;background: #fff;display: inline-block;vertical-align: middle;\" onerror=\"onerror=null;src='/assets/img/head.png'\" /></div>"
        + "</a> " +
        " </div> </div>"
    } else if (msgType == "opp" || msgType == "case") { // 商机信息、案例信息
      oppDivId = 'oppDivId' + new Date().getTime();
      const oppTitle = "<p style=\"font-size: 0.88rem;font-weight: 400;color: #252629;white-space:nowrap;padding-bottom: 0.63rem; white-space: nowrap;overflow: hidden;text-overflow: ellipsis; \"> " + contentObj.title + "</p>";
      let oppImag = "";
      if (contentObj.imags) {
        oppImag = "<img  src=\"" + contentObj.imags + "?x-oss-process=image/resize,h_140,w_211 \"" + "style=\"object-fit: cover;object-position: center;width: 13.19rem;height: 8.75rem; vertical-align: middle;\" onerror=\"onerror=null;src='/assets/img/default_rk.png'\" />";
      } else if (contentObj.pluginId === '1' ||
        contentObj.pluginId === '2' ||
        contentObj.pluginId === '4' ||
        contentObj.pluginId === '13' ||
        contentObj.pluginId === '15' ||
        contentObj.pluginId === '16' ||
        contentObj.pluginId === '17' ||
        contentObj.pluginId === '18' ||
        contentObj.pluginId === '26' ||
        contentObj.pluginId === '19' ||
        contentObj.pluginId === '20' ||
        contentObj.pluginId === '21' ||
        contentObj.pluginId === '22' ||
        contentObj.pluginId === '30') {
        oppImag = "<img  src=\"/assets/img/default_rk.png \"" + "style=\"object-fit: cover;object-position: center;width: 13.19rem;height: 8.75rem; vertical-align: middle;\" onerror=\"onerror=null;src='/assets/img/default_rk.png'\" />";
      }
      let industry = '';
      let oppSubTitle = '';
      if (contentObj.industry) {
        industry = contentObj.industry;
        oppSubTitle = "<p style=\"font-size: 1rem;font-weight: bold;color: #252629;white-space:nowrap;padding-bottom: 0.63rem;padding-top: 0.94rem;white-space: nowrap;overflow: hidden;text-overflow: ellipsis; \"> " + contentObj.big_district + contentObj.district + industry + "</p>";
      }
      if (this.isPxw === 'lj' || this.isPxw === 'js') {
        contentObj.type = "lj_opp";
      }
      const oppTag = "<div style=\"font-size: 0.75rem;font-weight: 400;color: #7E838C;white-space:nowrap;display: flex;align-items: center;overflow: hidden;\"> " + (contentObj.area ? contentObj.area + '㎡' : '') + (contentObj.rent ? "<div style=\"width: 0.03rem;height: 0.44rem;background: #B6B7BF;\"></div>" + contentObj.rent : '') + (contentObj.rentunit ? contentObj.rentunit : '') + "</div>";
      viewitem = "<div class=\"talkItem\" style=\"display: flex;width: 100%;justify-content: flex-end;margin-bottom: 1rem;\"> <div style=\"width: 3.5rem; height: 0.625rem;\"></div> "
        + " <div id=\"" + oppDivId + "\" onClick=\"window['chatService'].loadDetailPage('" + contentObj.type + "'," + contentObj.disableClick + "," + contentObj.pluginId + ",'" + contentObj.opportunity_id + "','" + contentObj.activity_reg_id + "')\" class=\"talkcontent  myTalkContentOPP\"  style=\"font-weight: 400;color: #252629;display: inline-block;vertical-align: top;text-align:left;background: #fff;width: -moz-fit-content;width: max-content;max-width:14.69rem;min-width:5rem;font-size: 1rem;line-height: 1.38rem;padding: 0.56rem 1rem;position: relative;white-space: pre-line;border-radius: 0.5rem 0 0.5rem 0.5rem;\"> "
        + oppTitle
        + oppImag
        + oppSubTitle
        + oppTag
        + " </div> <div class=\"avatorpanel\" "
        + "style=\"display: flex;flex-direction: column;align-items: center;margin-left: 0.5rem;\" "
        + "><a class=\"talkavator\">" + "<div class=\"windowImg marginR15L10\">"
        + "<img class=\"windowImg\" src=\"" + localStorage.getItem('currentAvatarStr')
        + "\""
        + "style=\"object-fit:unset;object-position: center;width: 2.5rem;height: 2.5rem;border-radius: 50%;background: #fff;display: inline-block;vertical-align: middle;\" onerror=\"onerror=null;src='/assets/img/head.png'\" /></div>"
        + "</a> " +
        " </div> </div>"
      // 2023.12.02 只有商机才创建
      // 2024.08.05 修复点击两次跳转到活动详情页面异常
    }
    if (document.getElementById("talkcontentlist")) {

      if (this.pageNo > 0 && fromSend == undefined) {
       
        document.getElementById("talkcontentlist").innerHTML = viewitem + document.getElementById("talkcontentlist").innerHTML;

        if (createTime !== null && createTime !== undefined) {
          document.getElementById("talkcontentlist").innerHTML = "<div style=\"font-size: 0.75rem;font-weight: 400;color: #7E838C;white-space:nowrap;display: flex;align-items: center;overflow: hidden;align-items: center;justify-content: center;padding-bottom: 1rem;\"> " + this.formatTimeLikeWeChat(createTime) + "</div>" + document.getElementById("talkcontentlist").innerHTML;
        }
      } else {
        if (createTime !== null && createTime !== undefined) {
          document.getElementById("talkcontentlist").innerHTML += "<div style=\"font-size: 0.75rem;font-weight: 400;color: #7E838C;white-space:nowrap;display: flex;align-items: center;overflow: hidden;align-items: center;justify-content: center;padding-bottom: 1rem;\"> " + this.formatTimeLikeWeChat(createTime) + "</div>"
        }
        document.getElementById("talkcontentlist").innerHTML += viewitem;
      }

    }
    if (document.getElementById("talk_end")) {
      document.getElementById("talk_end").scrollIntoView({ behavior: "smooth" });
    }
  }
  // 添加好友发送的内容 
  addFriendContentView(tempMsgChild, msgType, content, createTime?,fromSend?) {
    let that = this;
    var viewitem = ""
    const contentObj = JSON.parse(content);
    if (contentObj.type) {
      msgType = contentObj.type;
    }
    let oppDivId = '';
    if (msgType == "string" || msgType === "general") {
      viewitem = "<div  class=\"talkItem\" style=\" display: flex;width: 100%;margin-bottom: 1rem;\" > <div class=\"avatorpanel\" "
        + " style=\"display:flex;flex-direction:column;align-items: center;padding-right:0.5rem;\" > <div class=\"talkavator\">"
        + "<div class=\"windowImg marginR10L15\">"
        + "<img class=\"windowImg\" src=\"" + this.getAvatar(tempMsgChild.speaker)
        + "\" onerror=\"onerror=null;src='/assets/img/head.png'\""
        + "style=\"object-fit:unset;object-position: center;width: 2.5rem;height: 2.5rem;border-radius: 50%;background: #fff;display: inline-block;vertical-align: middle;\" /></div>"
        + "</div></div> "
        + " <div style=\"width: max-content;max-width: 14.69rem;min-width:5rem;\"><p style=\"font-size: 0.66rem;text-wrap: nowrap;color: #7E838C;padding-bottom: 0.13rem;\">" + this.currentGroupName + "</p> "
        + " <div class=\"talkcontent  friendContent\" "
        + " style=\"background:#FFF;font-weight: 400;color: #252629;width: -moz-fit-content;width: max-content;max-width: 14.69rem;min-width:5rem;font-size: 1rem;line-height: 1.38rem;padding: 0.56rem 1rem;position: relative;white-space: pre-line;border-radius: 0.31rem;margin-right: 0.5rem;\" >"
        + contentObj.message + "</div> " +
        " </div> </div>";
    } else if (msgType == "opp" || msgType == "case") { // 商机信息、案例信息
      oppDivId = 'oppFriendDivId' + new Date().getTime();
      const oppTitle = "<p style=\"font-size: 0.88rem;font-weight: 400;color: #252629;white-space:nowrap;padding-bottom: 0.63rem; white-space: nowrap;overflow: hidden;text-overflow: ellipsis; \"> " + contentObj.title + "</p>";
      let oppImag = "";

      if (contentObj.imags) {
        oppImag = "<img  src=\"" + contentObj.imags + "?x-oss-process=image/resize,h_140,w_211 \"" + "style=\"object-fit: cover;object-position: center;width: 13.19rem;height: 8.75rem; vertical-align: middle;\" onerror=\"onerror=null;src='/assets/img/default_rk.png'\" />";
      } else if (contentObj.pluginId === '1' ||
        contentObj.pluginId === '2' ||
        contentObj.pluginId === '4' ||
        contentObj.pluginId === '13' ||
        contentObj.pluginId === '15' ||
        contentObj.pluginId === '16' ||
        contentObj.pluginId === '17' ||
        contentObj.pluginId === '18' ||
        contentObj.pluginId === '26' ||
        contentObj.pluginId === '19' ||
        contentObj.pluginId === '20' ||
        contentObj.pluginId === '21' ||
        contentObj.pluginId === '22' ||
        contentObj.pluginId === '30'
        || contentObj.pluginId > '30'
      ) {
        oppImag = "<img  src=\"/assets/img/default_rk.png \"" + "style=\"object-fit: cover;object-position: center;width: 13.19rem;height: 8.75rem; vertical-align: middle;\" onerror=\"onerror=null;src='/assets/img/default_rk.png'\" />";
      }
      let industry = '';
      let oppSubTitle = '';
      if (contentObj.industry) {
        industry = contentObj.industry;
        oppSubTitle = "<p style=\"font-size: 1rem;font-weight: bold;color: #252629;white-space:nowrap;padding-bottom: 0.63rem;padding-top: 0.94rem;white-space: nowrap;overflow: hidden;text-overflow: ellipsis; \"> " + contentObj.big_district + contentObj.district + industry + "</p>";
      }
      if (this.isPxw === 'lj' || this.isPxw === 'js') {
        contentObj.type = "lj_opp";
      }
      const oppTag = "<div style=\"font-size: 0.75rem;font-weight: 400;color: #7E838C;white-space:nowrap;display: flex;align-items: center;overflow: hidden;\"> " + (contentObj.area ? contentObj.area + '㎡' : '') + (contentObj.rent ? "<div style=\"width: 0.03rem;height: 0.44rem;background: #B6B7BF;\"></div>" + contentObj.rent : '') + (contentObj.rentunit ? contentObj.rentunit : '') + "</div>";
      viewitem = "<div class=\"talkItem\" style=\"display: flex;width: 100%;justify-content: flex-start;margin-bottom: 1rem;\"> "
        + "<div class=\"avatorpanel\" "
        + "style=\"display: flex;flex-direction: column;align-items: center;margin-right: 0.5rem;\" "
        + "><div class=\"talkavator\">" + "<div class=\"windowImg marginR15L10\">"
        + "<img class=\"windowImg\" src=\"" + this.getAvatar(tempMsgChild.speaker)
        + "\""
        + "style=\"object-fit:unset;object-position: center;width: 2.5rem;height: 2.5rem;border-radius: 50%;background: #fff;display: inline-block;vertical-align: middle;\" onerror=\"onerror=null;src='/assets/img/head.png'\" /></div>"
        + "</div> " + " </div> "
        + " <div style=\"width: max-content;max-width: 14.69rem;min-width:5rem;\"><p style=\"font-size: 0.66rem;text-wrap: nowrap;color: #7E838C;padding-bottom: 0.13rem;\">" + this.currentGroupName + "</p> "
        + " <div id=\"" + oppDivId + "\" onClick=\"window['chatService'].loadDetailPage('" + contentObj.type + "'," + contentObj.disableClick + "," + contentObj.pluginId + ",'" + contentObj.opportunity_id + "','" + contentObj.activity_reg_id + "')\"  class=\"talkcontent  friendContentOPP\"  style=\"font-weight: 400;color: #252629;display: inline-block;vertical-align: top;text-align:left;background: #fff;width: -moz-fit-content;width: max-content;max-width:14.69rem;min-width:5rem;font-size: 1rem;line-height: 1.38rem;padding: 0.56rem 1rem;position: relative;white-space: pre-line;border-radius: 0.5rem 0 0.5rem 0.5rem;\"> "
        + oppTitle
        + oppImag
        + oppSubTitle
        + oppTag
        + " </div></div>" +
        "</div>"

    }

    if (document.getElementById("talkcontentlist")) {
      if (this.pageNo > 0 && fromSend ==undefined) {
        document.getElementById("talkcontentlist").innerHTML = viewitem + document.getElementById("talkcontentlist").innerHTML;

        if (createTime !== null && createTime !== undefined) {
          document.getElementById("talkcontentlist").innerHTML = "<div style=\"font-size: 0.75rem;font-weight: 400;color: #7E838C;white-space:nowrap;display: flex;align-items: center;overflow: hidden;align-items: center;justify-content: center;padding-bottom: 1rem;\"> " + this.formatTimeLikeWeChat(createTime) + "</div>" + document.getElementById("talkcontentlist").innerHTML;
        }

      } else {
        if (createTime !== null && createTime !== undefined) {
          document.getElementById("talkcontentlist").innerHTML += "<div style=\"font-size: 0.75rem;font-weight: 400;color: #7E838C;white-space:nowrap;display: flex;align-items: center;overflow: hidden;align-items: center;justify-content: center;padding-bottom: 1rem;\"> " + this.formatTimeLikeWeChat(createTime) + "</div>"
        }
        document.getElementById("talkcontentlist").innerHTML += viewitem;
      }

      // document.getElementById("talkcontentlist").appendChild(talkItemDiv);
    }
    if (document.getElementById("talk_end")) {
      document.getElementById("talk_end").scrollIntoView({ behavior: "smooth" });
    }
  }

  formatTimeLikeWeChat(timestamp) {
    const now = new Date().getTime(); // 当前时间  
    const diff = now - timestamp; // 时间差  
    const minute = 60 * 1000; // 一分钟  
    const hour = 60 * minute; // 一小时  
    const day = 24 * hour; // 一天  
    const month = 30 * day; // 一个月，这里简化为30天  
    const year = 12 * month; // 一年，这里简化为12个月  
    const diffNumber = Number(diff) || 0;
    const yearNumber = Number(year) || 1;

    let result = '';
    if (diffNumber < minute) {
      result = '刚刚';
    } else if (diffNumber < hour) {
      result = Math.floor(diffNumber / minute) + '分钟前';
    } else if (diffNumber < day) {
      result = Math.floor(diffNumber / hour) + '小时前';
    } else if (diffNumber < month) {
      result = Math.floor(diffNumber / day) + '天前';
    } else if (diffNumber < yearNumber) {
      result = Math.floor(diffNumber / month) + '个月前';
    } else {
      this.appGlobalService.consoleLog('formatTimeLikeWeChat=', diffNumber);
      result = Math.floor(diffNumber / yearNumber) + '年前';
    }
    if (this.appGlobalService.addedFormatTimes.has(result)) {
      result = '';
    } else {
      this.appGlobalService.addedFormatTimes.add(result);
    }
    return result;
  }


  // 2023.12.01 发送消息 
  sendMessage(data) {
    const that = this;
    const toId = data.toId;
    let content = data.text;
    const fromId = data.fromId;
    const key = data.key;
    const msgType = data.type;
    const title = data.title;

    const opportunity_id = data.opportunity_id ? data.opportunity_id : 0;
    const pic = data.pic;
    const plugin_id = data.plugin_id;
    const nowDate = data.nowDate;
    const clientSendTime = new Date().getTime();
    that.appGlobalService.addedMessages.add(clientSendTime);
    const generalContent = {
      type: "general",
      message: data.text,
      clientSendTime
    };
    const link = data.link;

    const toUserName = data.toUserName;
    const toUserId = data.toUserId;

    const oppContent = {
      auth: true,
      clientSendTime,
      opportunity_id,
      imags: data.imags,
      pluginId: data.pluginId,
      //新增参数
      activity_reg_id: data.activity_reg_id,
      title: data.title,
      big_district: data.big_district,
      district: data.district,
      area: data.area,
      industry: data.industry,
      rentunit: data.rentunit ? data.rentunit : "元/月",
      rent: data.rent,
      transfer_fee: data.transfer_fee,
      type: "opp",
    };

    if (data.disableClick !== undefined) {
      oppContent['disableClick'] = true;
    }

    const caseContent = {
      type: "case",
      text: data,
      clientSendTime,
      title: data.title,
      imags: data.imags,
      caseType: data.caseType,
      district: data.district,
      industry: data.industry,
      serviceDays: data.serviceDays,
      serviceOpinion: data.serviceOpinion,
      link,
    };
    const afterBody = oppContent;
    const afterCaseBody = caseContent;
    // generalContent; // 普通消息
    // oppContent;  // 商机消息
    // caseContent; // 案例消息
    let readyToSendMsg;
    try {
      switch (msgType) {
        case 'general':
          readyToSendMsg = generalContent;
          break;
        case 'opp':
          readyToSendMsg = oppContent;
          break;
        case 'case':
          readyToSendMsg = caseContent;
          break;
      }
      // 2024.07.04
      // 客户端发送数据格式
      // {
      // "header":"message",
      // "to":"1007",
      // "content":{ /* 这里是用户自定义的Json格式内容 */ }
      // }
      let jsonObj = {
        from: localStorage.getItem('userId'),
        header: 'message',
        content: readyToSendMsg,
        to: toId, // 接收者
      };

      that.appGlobalService.consoleLog('检查发送参数', jsonObj);
      if (this.ws.readyState === 3) {// WebSocket is already in CLOSING or CLOSED state.
        // this.appGlobalService.showToast('发送失败~',1500,'middle');
        // 没退出登录则更新状态
        that.closeWebSocket();
      } else {
        this.send(JSON.stringify(jsonObj));
      }
    } catch (err) {
      that.appGlobalService.consoleLog('操作异常', err);
      this.appGlobalService.showToast('发送失败~', 1500, 'middle');
    }
    const ifLogin = localStorage.getItem("userId") !== "null";
    if (ifLogin) {
      let tel = "";
      if (msgType === "general") {
        try {
          // 新增临时需求
          if (content.includes("tel:") && !content.includes("<font color=#499DF2 >")) {
            const startPos = content.search("tel:") + 4;
            tel = content.substring(startPos, startPos + 11);
            const afterReplaceText = "<font color=#499DF2 >" + tel + "</font>";
            content = content.replace(tel, afterReplaceText);
          } else if (content.includes("tel:") && content.includes("<font color=#499DF2 >")) {
            const startPos = content.search("<font color=#499DF2 >") + 21;
            tel = content.substring(startPos, startPos + 11);
          }
        } catch (error) {
          tel = "";
        }
      }

      const generalMsgArray = {
        msg:
        {
          type: "general",
          message: content + "",
          tel
        },
        datetime: that.getTime(),
      };

      const oppMsgArray = { msg: afterBody, datetime: that.getTime() };

      const caseMsgArray = { msg: afterCaseBody, datetime: that.getTime() };

      const singleGeneral = {
        msg: { type: "general", message: content + "", from: fromId },
        datetime: that.getTime(),
      };

      const singleCase = { msg: afterCaseBody, datetime: that.getTime() };

      let currentMsg = (msgType === "general"
        ? generalMsgArray
        : msgType === "opp"
          ? oppMsgArray
          : caseMsgArray);
      let tempLastMessageTime = localStorage.getItem('sendMsgLastTime');
      let currentTime = new Date().getTime();
      let lastMessageTime = Number(tempLastMessageTime);
      let showTimestamp = false;
      // // 检查当前消息和上一条消息的时间差是否大于3分钟  
      if (!lastMessageTime) {
        showTimestamp = true;
      } else {
        if ((currentTime - lastMessageTime > 3 * 60 * 1000)) {
          showTimestamp = true;
          lastMessageTime = currentTime; // 更新上一条消息的时间
          localStorage.setItem('sendMsgLastTime', currentTime.toString());
        } else {
          showTimestamp = false;
        }

      }
      const tempTime = showTimestamp ? currentTime : null;
      // 2023.12.01 转换消息格式
      this.addMyContentView(msgType, JSON.stringify(currentMsg.msg), tempTime,true);
    }
  }



  //关闭websocket链接
  closeWebSocket() {
    const that = this;
    // 清除心跳定时器  
    if (that.sendtimeObj) {
      clearTimeout(that.sendtimeObj);
      that.sendtimeObj = null;
      that.appGlobalService.consoleLog('清除心跳定时器完成', '');
    }
    that.close();
  }

  // 首页消息滚动
  homeMessageScroll(event) {
    event.preventDefault();
    if (event.target.scrollTop >= 1) {
      $('#messageNotify').fadeOut(600);
      $('#notifyBox').fadeOut(600);
      window['appGlobalService'].isShowMessageNotifyDiv = false;
    }
  }
  // 首页消息按钮处理
  homeMessageClick(event, fromUserId, fromUser) {
    this.appGlobalService.consoleLog('homeMessageClick?uid=', fromUserId);
    event.preventDefault();
    $('#messageNotify').fadeOut(600);
    $('#notifyBox').fadeOut(600);
    // $('.rightChat').click();
    window['appGlobalService'].isShowMessageNotifyDiv = false;
    if (fromUserId !== undefined) {
      localStorage.setItem('enterChatRoomByUserId', '1');
      this.eventService.eventEmit.emit('enterChatRoomByUserId',
        {
          userId: fromUserId,
          fromFriendList: true,
          friendName: fromUser ? fromUser.nickName : '',
          friendAvatar: fromUser.friendAvatar ? fromUser.friendAvatar : this.appGlobalService.defaultImg
        }
      );
    }


  }
  //添加成员内容
  addMemberContentView(memberSource: any) {
  }
  // 发送日志信息
  sendLog(msg) {
    // console.log('websocket:log:',msg);
    if (msg.includes('发送失败~')) {
      this.appGlobalService.showToast('发送失败~', 1500, 'middle');
      this.clearCustomTimeout();
      this.close();

      // 主动发起发送失败则重新链接
      return;
    }
    // document.getElementById("propmtid").innerText = msg
  }

  // 私聊记录
  insertTalkRecord(msg) {
    let len = this.myFriends.get(this.currentTalkSource).length
    this.myFriends.get(this.currentTalkSource)[len + 1] = msg
  }


  // 新增群聊记录
  insertGroupTalkRecord(tableName, msg, i, totalSize?) {
    const that = this;
    let contentJsonObj;
    if (msg.content) {
      contentJsonObj = JSON.parse(msg.content);
    }
    // 添加到数据库。
    try {
      const from = contentJsonObj.from;
      let jid = localStorage.getItem('userId');
      if (jid === null) {
        if (localStorage.getItem('loginAccount')) {
          jid = localStorage.getItem('loginAccount');
        } else {
          return;
        }
      }
      const type = 'general';
      let body = {
        message: '',
        pluginId: contentJsonObj.pluginId ? contentJsonObj.pluginId : '',
        imags: contentJsonObj.imags ? contentJsonObj.imags : '',
        pic: contentJsonObj.pic ? contentJsonObj.pic : '',
        rentunit: contentJsonObj.rentunit ? contentJsonObj.rentunit : '',
        title: contentJsonObj.title ? contentJsonObj.title : '',
        big_district: contentJsonObj.big_district ? contentJsonObj.big_district : '',
        district: contentJsonObj.district ? contentJsonObj.district : '',
        area: contentJsonObj.area ? contentJsonObj.area : '',
        industry: contentJsonObj.industry ? contentJsonObj.industry : '',
        build: contentJsonObj.build ? contentJsonObj.build : '',
        rent: contentJsonObj.rent ? contentJsonObj.rent : '',
        transfer_fee: contentJsonObj.transfer_fee ? contentJsonObj.transfer_fee : '',
        serviceOpinion: contentJsonObj.serviceOpinion ? contentJsonObj.serviceOpinion : '',
        serviceDays: contentJsonObj.serviceDays ? contentJsonObj.serviceDays : '',
        from,
        fromUserAvatar: contentJsonObj.fromUserAvatar,
        fromUserNickName: contentJsonObj.fromUserNickName,
        type: contentJsonObj.type
      };
      if (contentJsonObj.disableClick !== undefined) {
        body['disableClick'] = contentJsonObj.disableClick;
      }
      body.message = contentJsonObj.message;
      let datetime;
      try {
        datetime = this.appGlobalService.getNowFormatDateYYYYMMDDHHMM(msg.createTime);
      } catch (e) {
        datetime = this.appGlobalService.getNowFormatDateYYYYMMDDHHMM();
        that.appGlobalService.consoleLog('datetime error', e);

      }
      let msgType = contentJsonObj.type;
      let pluginId = "1"; // 1 转让 2 求租 3 招租
      let opportunityId = 0;
      const title = "";

      let pic = "";
      let message;
      let res = msg.listener;// 统一为groupId
      if (msgType === "opp") {
        opportunityId = 0;
        pluginId = body.pluginId;
        pic = body.imags;
      } else if (msgType === "case") {
        pic = body.pic;
      }

      let tel = "";
      if (msgType === "general") {
        try {
          // 新增临时需求
          if (body.message.includes("&lt;font color=#499DF2 &gt;")) {
            const startPos =
              body.message.search("tel:&lt;font color=#499DF2 &gt;") +
              31;
            tel = body.message.substring(startPos, startPos + 11);
            const afterReplaceText =
              "<font color=#499DF2 >" + tel + "</font>";
            const replaceTel =
              "tel:&lt;font color=#499DF2 &gt;" +
              tel +
              "&lt;/font&gt;";
            body.message = body.message.replace(
              replaceTel,
              afterReplaceText
            );

            body["tel"] = tel;
          } else {
            if (body.message.includes("tel:")) {
              const startPos = body.message.search("tel:") + 4;
              tel = body.message.substring(startPos, startPos + 11);
              const afterReplaceText =
                "<font color=#499DF2 >" + tel + "</font>";
              body.message = body.message.replace(
                tel,
                afterReplaceText
              );

              body["tel"] = tel;
            }
          }
        } catch (error) {
          tel = "";
        }
      }

      message =
        msgType === "general"
          ? {
            id: res + "-" + jid,
            senderId: contentJsonObj.from,
            text: body,
            type: msgType,
            time: datetime,
          }
          : msgType === "opp"
            ? {
              id: res + "-" + jid,
              senderId: contentJsonObj.from,
              type: msgType,
              rentunit: body.rentunit ? body.rentunit : "元/月",
              opportunity_id: opportunityId,
              title: body.title,
              pic: body.imags,
              pluginId,
              time: datetime,
              big_district: body.big_district,
              district: body.district,
              area: body.area,
              industry:
                pluginId === "1" ? body.industry : body.build,
              rent: body.rent,
              transfer_fee: body.transfer_fee
                ? body.transfer_fee
                : undefined,
            }
            : {
              id: res + "-" + jid,
              senderId: contentJsonObj.from,
              type: msgType,
              title: body.title,
              imags: body.imags,
              time: datetime,
              district: body.district,
              serviceOpinion: body.serviceOpinion,
              serviceDays: body.serviceDays,
              industry: body.industry,
            };
      const storageKey = res + "-" + jid;
      const tempInsertObj = {
        msg: msgType === 'general' ? {
          type: msgType,
          message: body.message,
          from: contentJsonObj.from, // 由groupId改为userId
          tel,
        } : { type: msgType, message: message.title, from: contentJsonObj.from },// 由groupId改为userId
        datetime,
        number: 0,
        isNew: 0,
        updateTime: new Date().getTime(),
        toUserId: msg.listener,
        toUserName: this.currentGroupName,
        fromUserMobile: this.enterTheChatRoomUseUserId,
        toUserIcon: contentJsonObj.fromUserAvatar
      };
      if (tableName === 'chat') {
        this.indexedDBService.addCallbak(
          { msg: body, datetime },
          storageKey + "-" + Date.now() + i,
          "chat",
          () => {
            that.appGlobalService.consoleLog('totalSize=', totalSize);
            that.appGlobalService.consoleLog('i=', i);
            if (totalSize && (totalSize - 1) === i) {
              this.eventService.eventEmit.emit("refreshChatMsg", "1");
            }
          });
      } else if (tableName === 'unreadchat') {
        this.indexedDBService.putByKeyCallbak(
          tempInsertObj,
          storageKey,
          "unreadchat",
          () => {
            this.chatListArray.push(tempInsertObj);
          });
      }
      // }
      // }
    } catch (error) {
    }
  }

  start() {
    const that = this;
    // tslint:disable-next-line:no-unused-expression
    this.sendtimeObj && clearTimeout(this.sendtimeObj);
    // tslint:disable-next-line:no-unused-expression
    this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
    this.sendtimeObj = setTimeout(() => {
      if (this.ws !== undefined) {
        that.appGlobalService.consoleLog('开始发送Ping...', '  	   ');
        this.send(this.pingStr);
      }
    }, this.timeout);
  }


  // 清除心跳定时器
  clearCustomTimeout() {
    if (this.sendtimeObj) {
      clearTimeout(this.sendtimeObj);
      this.sendtimeObj = null;
      this.appGlobalService.consoleLog('清除心跳定时器', '  	   ')
    }

  }

  // websocket 关闭
  wsLogout() {
    this.clearCustomTimeout();
    if (this.ws !== undefined) {
      this.closeWebSocket();
    }
  }

  // 格式化聊天时间
  getFormatImDate(value) {
    try {
      value = value.replace(/\-/g, "/");
      const nowDate = new Date();
      const prettyDate = new Date(value);
      const nowTime = new Date().getTime() / 1000;
      const prettyTime = prettyDate.getTime() / 1000;
      const diff = nowTime - prettyTime;
      if (diff >= 0 && diff < 300) {        // 刚刚：5分钟之内
        return this.formatDate(prettyDate, "hh:mm");
      } else if (prettyDate.getTime() > this.beginOfToday() && diff < 24 * 60 * 60) { // 小时前：一天之内
        return this.formatDate(prettyDate, "hh:mm");
      } else if (prettyDate.getTime() > this.beginOfYesterday() && prettyDate.getTime() < this.beginOfToday()) {
        return "昨天";
      } else if (prettyDate.getTime() > this.beginOfThisWeek() && prettyDate.getTime() < this.beginOfYesterday()) {// 一周内
        const week = new Array("日", "一", "二", "三", "四", "五", "六");
        return "星期" + week[new Date(prettyDate).getDay()];
      } else if (nowDate.getFullYear() === prettyDate.getFullYear()) {// 具体日期：超过一个月，本年度内 月 - 日（示例：08 - 08）
        return this.formatDate(prettyDate, "MM-dd");
      } else { // 具体日期：去年 （示例：2014 - 08 - 08）
        return this.formatDate(prettyDate, "yyyy-MM-dd hh:mm");
      }
    } catch (error) {
      return this.formatDate(new Date(), "hh:mm");
    }

  }

  beginOfThisWeek() {
    const mydate = new Date();
    return new Date(this.beginOfToday()).getTime() - (mydate.getDay()) * (24 * 60 * 60 * 1000);
  }

  beginOfToday() {
    const mydate = new Date();
    let myyear, mymonth, myday, mytime;
    myyear = mydate.getFullYear();
    mymonth = (mydate.getMonth() + 1) < 10 ? '0' + (mydate.getMonth() + 1) : mydate.getMonth() + 1;
    myday = mydate.getDate() < 10 ? '0' + mydate.getDate() : mydate.getDate();
    mytime = myyear + "-" + mymonth + "-" + myday + " 00:00:00";
    return (new Date(mytime).getTime());
  }

  beginOfYesterday() {
    return new Date(this.beginOfToday()).getTime() - (24 * 60 * 60 * 1000);
  }
  formatDate = (dateToFormat, format) => {
    const date = {
      "M+": dateToFormat.getMonth() + 1,
      "d+": dateToFormat.getDate(),
      "h+": dateToFormat.getHours(),
      "m+": dateToFormat.getMinutes(),
      "s+": dateToFormat.getSeconds(),
      "q+": Math.floor((dateToFormat.getMonth() + 3) / 3),
      "S+": dateToFormat.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
      format = format.replace(RegExp.$1, (dateToFormat.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (const k in date) {
      if (new RegExp("(" + k + ")").test(format)) {
        format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
      }
    }
    return format;
  }

  // 获取指定格式时间
  getTime() {
    return this.appGlobalService.getNowFormatDateYYYYMMDDHHMM();
  }

  // 2024.07.02 获取我的好友列表请求参数
  getPaginationParamStr(uid, pageSize, pageNo, friendNo?, timeLine?) {
    let userId: any;
    if (uid) {
      userId = uid;
    }

    let tempString = this.pkey + userId;
    if (friendNo !== undefined) {
      tempString = tempString + friendNo;
    }
    const singStr = CryptoJS.MD5(tempString).toString();
    let url = '?userId=' + userId
      + '&key=' + singStr
      + '&pageNo=' + pageNo
      + '&pageSize=' + pageSize;

    if (friendNo !== undefined) {
      url = '?userId=' + userId
        + '&friendId=' + friendNo
        + '&key=' + singStr
        + '&pageNo=' + pageNo
        + '&pageSize=' + pageSize;
      if (pageNo === 0) {
        url = url + '&timeLine=';
      } else {
        url = url + '&timeLine=' + timeLine;
      }
    }
    return url;
  }


  // 2024.07.02 处理好友列表数据
  getProcessSingleMsg(uid, ele) {
    //   {
    //     "friendName": "铺铺旺集团沈望明",
    //     "friendAvatar": "http://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_1c48e2c6d3f93a5553c92d1fbb3cb175.jpg",
    //     "friendNo": "375949ca0f9c11eab63a0242ac160002",
    //     "hasNoRead": false
    // }
    let from: any;
    let message: any;
    let avatar_url: any;
    let fromUserMobile: any;

    from = ele.friendNo; // 好友userId 
    message = null; // 先不展示一条最近的消息
    avatar_url = ele.friendAvatar ? ele.friendAvatar : 'assets/img/head.png';
    fromUserMobile = '';

    // 20231008取userId
    let currentUserId = localStorage.getItem('userId');
    let currentAccount = localStorage.getItem('loginAccount');
    let singleMsg = {
      toId: ele.friendNo,
      toUserName: ele.friendName,
      currentAccount,
      groupNo: ele.friendNo,
      key: ele.friendNo + '-' + currentUserId,
      id: ele.friendNo + '-' + currentUserId,
      msg: { message: message, from: from },
      isNew: ele.hasNoRead ? 1 : 0, // ele.hasNoRead,// 2023.12.01 如果多台设备同时登录则isNew会失效，所以以有oringalMsg为准，点击进入则将isNew设置为 false
      avatar_url: avatar_url,
      nickname: ele.friendName,
      groupName: ele.friendName,
      updateTime: '',
      datetime: '',
      number: 0
    };
    return singleMsg;
  }




  getUserDataById(id, callbackFunction) {
    const that = this;
    this.http.get("message/userinfo/im/" + id, (response) => {
      if (response.status === 'success') {
        const data = response.data;
        callbackFunction(data);
      } else {
        callbackFunction(null);
      }
    }, (error) => {
      that.appGlobalService.consoleLog('msg-----> error:', error);
      callbackFunction(null);
    });
  }




  //发送命令进入群聊
  sendCommandEnterGroupByMemberNo(memberNo, visitorId, callBackFunction) {
    var comm = {
      category: "command",
      msgType: "enterGroup",
      speaker: visitorId,    // account表示游客身份的身份ID
      listener: memberNo,  // memberNo表示 目标客服的手机号码
      content: "",
      isGroup: true
    }
    this.enterGroupCallBacktion = callBackFunction;
    this.send(JSON.stringify(comm));

  }

  // 注册会话
  onRegisterWebSocket() {
    if (this.eventService.eventEmit.listenerCount("onRegisterWebSocket") > 0) {
      this.eventService.eventEmit.removeListener("onRegisterWebSocket");
    }
    this.eventService.eventEmit.on("onRegisterWebSocket", (data) => {
      if (localStorage.getItem("onRegisterWebSocketTag")) {
        localStorage.removeItem("onRegisterWebSocketTag");

      }
    });
  }



  // 读取好友
  sendCommandFriends() {
    let comm = {
      category: "command",
      msgType: "readFriends",
      speaker: localStorage.getItem('loginAccount')
    }
    this.send(JSON.stringify(comm));
  }


  // 确认覆盖登录
  sendCommandPowerLogin() {
    let comm = {
      category: "command",
      msgType: "powerLogin",
      speaker: localStorage.getItem('loginAccount')
    }
    this.send(JSON.stringify(comm));
  }

  // 添加好友
  sendCommandAppendFriend(friendNo) {
    if (friendNo != localStorage.getItem('loginAccount')) {
      const comm = {
        category: "command",
        msgType: "appendFriend",
        speaker: localStorage.getItem('loginAccount'),
        content: friendNo
      }
      this.send(JSON.stringify(comm));
    } else {
      this.sendLog("不能加自己为好友");
    }
  }

  // 删除好友
  sendCommandRemoveFriend(friendNo) {
    if (friendNo != localStorage.getItem('loginAccount')) {
      const comm = {
        category: "command",
        msgType: "removeFriend",
        speaker: localStorage.getItem('loginAccount'),
        content: friendNo
      }
      this.send(JSON.stringify(comm));
    } else {
      this.sendLog("不能删除自己")
    }
  }

  // 20231007-获取聊天记录
  async getChatHistoriesByFriendNo(friendNo, callBackFunction, newPageNo?) {
    const that = this;
    if (friendNo !== undefined) {
      let result = [];
      let uid = localStorage.getItem('userId');
      let pageSize = that.pageSize;
      let pageNo = 0;
      this.http.isLoading = true;
      if (newPageNo === undefined) {
        this.lastPageItems = [];
        this.http.delayShowLoading();
      } else {
        pageNo = newPageNo;
      }


      const url = that.http.talkQueryHistoriesList + that.getPaginationParamStr(uid, pageSize, pageNo, friendNo, this.lastTimeLine);
      this.getGetData(url, async (response) => {
        if (response) {
          const data = JSON.parse(response);

          if (data && data.listData !== undefined && data.listData.length > 0) {

            if (data.listData.length <= data.pageSize) {
              that.pageNo = data.pageNo;
            }
            if (data.timeLine) {
              this.lastTimeLine = data.timeLine;
            }

            if (this.lastPageItems && this.lastPageItems.length == 0) { //首页
              this.lastPageItems = data.listData;
            } else if (this.lastPageItems && this.lastPageItems.length > 0) {
              data.listData = this.lastPageItems.concat(data.listData);
            }
            let tempList = data.listData.sort((a, b) => {
              // ios上需要替换为iphone手机能够识别的时间格式 例如2024/08/09 17:52
              let dateA = new Date(a.createTime.replace(/-/g, '/')), dateB = new Date(b.createTime.replace(/-/g, '/'));
              return dateA.getTime() - dateB.getTime();
            });
            // this.appGlobalService.consoleLog('tempList=', tempList);
            this.appGlobalService.consoleLog('  	   ', tempList);
            if (tempList && tempList.length > 0) {
              const tempTime = localStorage.getItem('recevieMsgLastTime');
              let lastMessageTime = Number(tempTime);
              await that.processMessages(tempList, lastMessageTime);
              callBackFunction(data);
            } else {
              callBackFunction(null);
            }
          } else {
            that.pageNo = data.pageNo - 1;
            callBackFunction(null);
          }
        }
      });
    } else {
      this.appGlobalService.consoleLog('获取聊天记录', friendNo);
    }
  }

  async processMessages(tempList, lastMessageTime) {
    const that = this;
    for (let index = 0; index < tempList.length; index++) {
      let tempMsgChild = tempList[index];
      let tempContent = JSON.parse(tempMsgChild.content);
      // let currentTime = new Date(tempMsgChild.createTime).getTime();
      let dateTimeStr = tempMsgChild.createTime;
      let createTimeStr = dateTimeStr.replace(/-/g, '/');
      let currentTime = new Date(createTimeStr).getTime();
      let showTimestamp = true;

      if (!lastMessageTime) {
        if (!localStorage.getItem('recevieMsgLastTime')) {
          // 初始化接收时间如果不存在取第一条收到的信息
          localStorage.setItem('recevieMsgLastTime', currentTime.toString());
        }
      }
      // 检查消息是否已添加    
      if (!that.appGlobalService.addedMessages.has(currentTime)) {
        const convertObj = JSON.parse(tempMsgChild.content);
        if (convertObj && convertObj.clientSendTime
          && that.appGlobalService.addedMessages.has(convertObj.clientSendTime)) {
          continue;
        } else {
          that.appGlobalService.addedMessages.add(currentTime);
          let tempTime = showTimestamp ? currentTime : null;
          if (localStorage.getItem('userId') == tempMsgChild.speaker) {
            this.addMyContentView(tempMsgChild.msgType, tempMsgChild.content, tempTime);
          } else {
            // 好友的消息记录
            this.addFriendContentView(tempMsgChild, tempMsgChild.msgType, tempMsgChild.content, tempTime);
          }
        }
      }
    }
  }




  getGetData(url, callFunction) {
    let result: any; // 下载文件大小
    try {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            result = xhr.responseText;
            callFunction(result);
          }
        }
      };
      xhr.send();
    } catch (error) {
      console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  error=	   ', error);
      callFunction(result);
    }
  }


  // 刷新好友列表数据
  async refreshMyFriendData() {
    this.appGlobalService.consoleLog('onResume 刷新好友列表数据', '  	   ');
    let that = this;
    if (localStorage.getItem('userId') && localStorage.getItem('loginStatus')) {
      const url = this.http.talkQueryFriendsList + this.getPaginationParamStr(localStorage.getItem('userId'), this.pageSize, this.pageNo);
      this.getGetData(url, (response) => {
        if (response) {
          try {
            const data = JSON.parse(response);
            if (data && data.listData && data.listData.length > 0) {
              that.setMyFriendData(data);
            }
          } catch (e) {
            that.appGlobalService.consoleLog('解析响应数据时出错:', e);
          }
        }
      });
    }
  }

  createObservableSocket(url: string): Observable<any> {
    // 已经打开或正在连接，不能重连，返回一个不发射任何数据的Observable

    if (this.ws &&
      (this.ws.readyState === WebSocket.OPEN
        || this.ws.readyState === WebSocket.CONNECTING || this.ws.readyState === WebSocket.CLOSING)) {
      console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds()
        + '  	已经打开或者正处于连接中...，Returning an empty Observable.  ', '  	   ');
      return EMPTY; // EMPTY是RxJS中的一个特殊Observable，它不发射任何数据，直接完成。

    }

    this.ws = new WebSocket(url);
    return new Observable(observer => {
      // 成功返回数据
      this.ws.onmessage = (event) => {
        observer.next(event.data); // 通常我们只对数据感兴趣，所以这里只发射event.data
      };

      // 返回数据失败，抛出异常
      this.ws.onerror = (event) => {
        console.log(new Date().toLocaleString()
          + '.'
          + new Date().getMilliseconds() + ' 返回数据异常 ', event);
        observer.error(event);

      };

      // 关闭连接
      this.ws.onclose = (event) => {
        console.log(new Date().toLocaleString()
          + '.' + new Date().getMilliseconds()
          + ' 关闭连接 ', event);
        observer.complete();
      };

      return () => {
        if (this.ws && this.ws.readyState !== WebSocket.CLOSED) {
          this.ws.close(); // 当Observable被取消订阅时，关闭WebSocket连接。
        }
      };
    });
  }

  send(message: any, CallBackFunction?) {
    // tslint:disable-next-line:prefer-const
    if (this.ws) {
      this.appGlobalService.consoleLog('系统:发送前检查websocket状态', this.ws.readyState);
      if (this.ws.readyState === 1) {
        this.ws.send(message);
      } else {
        this.appGlobalService.consoleLog('系统:发送中状态异常一：', this.ws.readyState);
        // 执行重连
        this.reconnect();
      }
    } else {
      this.appGlobalService.consoleLog('系统:发送中状态异常二：', this.ws.readyState);
      // 执行重连
      this.reconnect();
    }
  }
  setAvatar(userId: string, avatarBase64: string): void {
    this.avatars[userId] = avatarBase64;
  }

  // 获取缓存中的头像
  getAvatar(userId: string, url?): string | undefined {
    let that = this;
    if (that.avatars[userId]) {
      return that.avatars[userId];
    } else {
      return null;
    }
  }

  close() {
    if (this.ws) {
      this.ws.close();
      this.appGlobalService.consoleLog('close websocket!', '  	   ');
    }
  }


}
